<template>
  <div class="condition-select">
    <el-text v-if="title" class="condition-select__title" :class="{ 'font-bold': boldTitle }">
      {{ title }}
    </el-text>
    <div class="condition-select__content">
      <el-text
        v-for="(tag, idx) in options"
        :key="idx"
        :class="{
          active: isActive(tag[keyProps.value]),
        }"
        class="condition-select__content--tag"
        @click.stop="handleChangeCondition(tag)"
      >
        {{ tag[keyProps.label] }}
      </el-text>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { conditionSelectProps, IReceiveConditionData } from './types';

defineOptions({ name: 'ConditionSelect' });

const props = defineProps(conditionSelectProps);
const emits = defineEmits(['update:modelValue', 'change']);

// 判断是否选中
const isActive = (tagVal: string) => {
  const { modelValue } = props;
  // 多选数组情况
  if (Array.isArray(modelValue)) {
    return modelValue.includes(tagVal);
  }
  return modelValue === tagVal;
};

// 点击选项变化
const handleChangeCondition = (tag: IReceiveConditionData) => {
  const { modelValue, keyProps, multiple, clearable, incompat } = props;
  const tagVal = tag[keyProps.value];
  // 单选
  if (!multiple) {
    // 可清除
    if (clearable) {
      // 当前modelValue和点击tag的value相等，要清空值
      if (modelValue === tagVal) {
        emits('update:modelValue', '');
        emits('change', '', tag);
      }
      if (modelValue !== tagVal) {
        emits('update:modelValue', tagVal);
        emits('change', tagVal, tag);
      }
    }
    // 不可清除
    if (!clearable) {
      emits('update:modelValue', tagVal);
      emits('change', tagVal, tag);
    }
  }
  // 复选
  if (multiple) {
    let list = [...modelValue];
    if (Array.isArray(list)) {
      const tarIndex = list.findIndex((val) => val === tagVal);
      if (tarIndex >= 0) {
        list.splice(tarIndex, 1);
      }
      if (tarIndex === -1) {
        list.push(tagVal);
      }
      // 互斥项 判断
      if (incompat !== undefined) {
        if (tagVal === incompat) {
          list = [incompat];
        } else {
          const idx = list.indexOf(incompat);
          if (idx > -1) {
            list.splice(idx, 1);
          }
        }
      }
      emits('update:modelValue', list);
      emits('change', list, tag);
    }
  }
};
</script>

<style lang="scss" scoped>
.condition-select {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  line-height: 26px;

  &__title {
    &.font-bold {
      font-weight: 600;
    }
  }

  &__content {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    align-items: center;
  }

  &__content--tag {
    padding: 0 10px;
    margin-right: 5px;
    cursor: pointer;
    user-select: none;
    border-radius: var(--border-radius);
    opacity: 0.8;
    transition: background 0.2s;

    &.active {
      color: var(--el-color-white);
      background: var(--el-color-primary);
      opacity: 1;
    }
  }
}
</style>
